﻿using System;
using System.IO;
using System.ServiceProcess;

using DreamCube.Foundation.Basic.Utility;
using DreamCube.Framework.Utilities.BasicObject;
using DreamCube.WebServer.WebHost;
using DreamCube.WebServer.WinServiceModel;

namespace DreamCube.WebServer.WinService
{
    public partial class VirtualIISServer : ServiceBase
    {
        private Server webServer = null;

        public VirtualIISServer()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 服务启动的时候调用的方法
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(String[] args)
        {
            DoStartServer();
        }

        /// <summary>
        /// 服务停止的时候调用的事件
        /// </summary>
        protected override void OnStop()
        {
            try
            {
                if (webServer != null)
                {
                    webServer.Stop();
                    webServer = null;
                }
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }

        /// <summary>
        /// 启动IIS服务
        /// </summary>
        private void DoStartServer()
        {
            try
            {
                if (webServer != null) return;
                String json = MyObject.ToStringEx(MyRegistry.Basic.GetLocalMachineSubKeyPropertyValue(Common.ConfigDataRegistryKey, Common.ConfigDataPropertyName));
                if (!String.IsNullOrEmpty(json))
                {
                    ServerConfig config = ObjectXHelper.CreateObjFromJSON<ServerConfig>(json);
                    if (config != null)
                    {
                        ValidateConfigData(config);
                        CopyDll(config.HostDllFilePath, config.WebPhysicalPath); //先复制依赖的dll
                        webServer = new Server(config.Port, config.WebVirtualPath, config.WebPhysicalPath, false, false, config.DefaultDos);
                        webServer.Start();
                    }
                }
                else
                {
                    MyLog.MakeLog("请配置web的相关信息再启动服务器！", MyLog.LogType.Exception);
                    throw new Exception("请配置web的相关信息再启动服务器！");
                }
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
                throw;
            }
        }

        /// <summary>
        /// 验证配置的数据是否合法
        /// </summary>
        /// <param name="config"></param>
        protected void ValidateConfigData(ServerConfig config)
        {
            //Int32 port = 80;
            if (!(config.Port >= 1 && config.Port <= 60000))
                throw new Exception("端口号必须为1-60000！");
            if (String.IsNullOrEmpty(config.WebPhysicalPath) || !Directory.Exists(config.WebPhysicalPath))
                throw new Exception("指定的网站目录不存在！");
            if (String.IsNullOrEmpty(config.HostDllFilePath) || !File.Exists(config.HostDllFilePath))
                throw new Exception("指定的承载Dll文件不存在！");
        }

        /// <summary>
        /// 确保删除了dll，否则影响IIS的部署
        /// </summary>
        private void DeleteDll(String hostFilePath, String webPath)
        {
            String fileName = MyString.LeftOfLast(hostFilePath, "\\");
            String path = Path.Combine(Path.Combine(webPath, "bin"), fileName);
            MyIO.TryDeleteFile(path);
        }

        /// <summary>
        /// 复制依赖的dll和调试的pdb
        /// </summary>
        private void CopyDll(String hostFilePath, String webPath)
        {
            if (String.IsNullOrEmpty(hostFilePath) || String.IsNullOrEmpty(webPath))
            {
                throw new Exception("您没有配置好网站的信息！");
            }
            else
            {
                if (File.Exists(hostFilePath))
                {
                    MyIO.FileCopy(hostFilePath, Path.Combine(webPath, "bin"), true, "");
                }
                else
                {
                    throw new Exception("承载服务器的dll找不到，联系管理员！");
                }
            }
        }
    }
}
